package com.xiaoshuidi.cloud.module.report.service.ajreport;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.oss.core.OosFileService;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.report.controller.ajreport.vo.*;
import com.xiaoshuidi.cloud.module.report.controller.finance.vo.ExportRespVO;
import com.xiaoshuidi.cloud.module.report.convert.ajreport.ReportPaymentDetailsConvert;
import com.xiaoshuidi.cloud.module.report.convert.ajreport.ReportRentPeriodDetailsConvert;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReportLedgerInfoDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReportPaymentDetailsDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReportRentPeriodDetailsDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.ReportPaymentDetailsMapper;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.ReportRentPeriodDetailsMapper;
import com.xiaoshuidi.cloud.module.report.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.report.framework.security.config.ConfigValues;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class ReportPaymentDetailsServiceImpl implements ReportPaymentDetailsService{

    private final ReportPaymentDetailsMapper reportPaymentDetailsMapper;
    private final ConfigValues configValues;
    private final OosFileService oosFileService;
    /**
     * 预定台账列表查询
     */
    public ReportPaymentDetailsRespVO page(ReportPaymentDetailsReqVO reqVO){
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        Page<ReportPaymentDetailsDO> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());
        LambdaQueryWrapper<ReportPaymentDetailsDO> queryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(reqVO.getApartmentId())) {
            queryWrapper.eq(ReportPaymentDetailsDO::getApartmentId, reqVO.getApartmentId());
        }
        if(!ObjectUtils.isEmpty(reqVO.getContractStartDateE())&&!ObjectUtils.isEmpty(reqVO.getContractStartDateS())){
            queryWrapper.le(ReportPaymentDetailsDO::getContractStartTime,reqVO.getContractStartDateE());
            queryWrapper.ge(ReportPaymentDetailsDO::getContractStartTime,reqVO.getContractStartDateS());
        }
        if(!ObjectUtils.isEmpty(reqVO.getContractEndDateS())&&!ObjectUtils.isEmpty(reqVO.getContractEndDateE())){
            queryWrapper.le(ReportPaymentDetailsDO::getContractEndTime,reqVO.getContractEndDateE());
            queryWrapper.ge(ReportPaymentDetailsDO::getContractEndTime,reqVO.getContractEndDateS());
        }
        if(!ObjectUtils.isEmpty(reqVO.getPayDateE())&&!ObjectUtils.isEmpty(reqVO.getPayDateS())){
            queryWrapper.le(ReportPaymentDetailsDO::getActualPayTime,reqVO.getPayDateE());
            queryWrapper.ge(ReportPaymentDetailsDO::getActualPayTime,reqVO.getPayDateS());
        }
        if (StringUtils.isNotBlank(reqVO.getArea())) {
            queryWrapper.like(ReportPaymentDetailsDO::getArea, reqVO.getArea());
        }
        if (StringUtils.isNotBlank(reqVO.getMixQueryParam())) {
            queryWrapper.and(wrapper -> wrapper.like(ReportPaymentDetailsDO::getPayer, reqVO.getMixQueryParam()).or()
                    .like(ReportPaymentDetailsDO::getHouseResource, reqVO.getMixQueryParam())
                    .or()
                    .like(ReportPaymentDetailsDO::getCustomerName, reqVO.getMixQueryParam()));
        }
        queryWrapper.eq(ReportPaymentDetailsDO::getTenantId,loginUser.getTenantId());
        queryWrapper.orderByDesc(ReportPaymentDetailsDO::getActualPayTime);
        queryWrapper.eq(ReportPaymentDetailsDO::getHandleFlag,1);
        page = reportPaymentDetailsMapper.selectPage(page, queryWrapper);
        reqVO.setTenantId(loginUser.getTenantId());
        ReportPaymentDetailsRespVO reportPaymentDetailsRespVO = reportPaymentDetailsMapper.selectSumAmount(reqVO);
        if(page.getTotal()==0L){
            PageResult<ReportPaymentData> result = new PageResult<>(0L);
            if(reportPaymentDetailsRespVO==null){
                reportPaymentDetailsRespVO = new ReportPaymentDetailsRespVO();
            }
            reportPaymentDetailsRespVO.setReportPaymentData(result);
            return reportPaymentDetailsRespVO;
        }
        PageResult<ReportPaymentDetailsDO> pageResult = new PageResult<>(page.getRecords(), page.getTotal());
        PageResult<ReportPaymentData> result = ReportPaymentDetailsConvert.INSTANCE.convertPage(pageResult);
        reportPaymentDetailsRespVO.setReportPaymentData(result);
        return reportPaymentDetailsRespVO;
    }

    /**
     * 预定台账表导出
     */
    public ExportRespVO export(ReportPaymentDetailsReqVO req){
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        req.setTenantId(loginUser.getTenantId());
        long count = reportPaymentDetailsMapper.countRentDetailsForExport(req);
        if (count <= 0) {
            throw new ServiceException(ErrorCodeConstants.PAYMENT_NOT_EXISTS);
        }
        int pageSize = 2000;
        int totalPage = (int) count / pageSize;
        if (count % pageSize != 0) {
            totalPage++;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String format = sdf.format(new Date());
        String fileName = format + "收款明细明细表.xlsx";

        String filePath = configValues.getNfsPath() + File.separator + fileName;
        ExcelWriter excelWriter = EasyExcel.write(filePath, ReportPaymentDetailsExportVO.class).build();
        WriteSheet sheet = EasyExcel.writerSheet("sheet1").build();
        for (int i = 1; i <= totalPage; i++) {
            List<ReportPaymentDetailsDO> infoDOList = reportPaymentDetailsMapper.selectRentDetailsForExport(req, (i - 1) * pageSize, pageSize);
            List<ReportPaymentDetailsExportVO> list = ReportPaymentDetailsConvert.INSTANCE.convertList(infoDOList);
            list.forEach(e->{});

            excelWriter.write(list, sheet);
        }
        excelWriter.finish();
        //上传到oos返回URL
        String url = oosFileService.oosUploadFile(new File(filePath));
        ExportRespVO resp = new ExportRespVO();
        if(url.startsWith("http:")){
            url = url.replace("http:","https:");
        }
        resp.setUrl(url);
        resp.setFileName(fileName);
        return resp;
    }

    @Override
    public List<ReportPaymentDetailsDO> selectUnHandle() {
        return reportPaymentDetailsMapper.selectUnHandle();
    }

    @Override
    public void updateRepeatByOrderId(Long orderId) {
         reportPaymentDetailsMapper.updateRepeatByOrderId(orderId);
    }

    @Override
    public void updateBatch(List<ReportPaymentDetailsDO> list) {
        reportPaymentDetailsMapper.updateBatch(list,list.size());
    }
}
